package com.jsgt.greekfire.ui.home

import android.app.Activity.RESULT_OK
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fhx.core.base.BaseFragment
import com.fhx.core.goToActivity
import com.fhx.core.goToActivityForResult
import com.fhx.core.utils.DialogUtil
import com.fhx.core.utils.LogUtils
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.App
import com.jsgt.greekfire.IS_ACTIVATION
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.BannerBean
import com.jsgt.greekfire.bean.MenuEntity
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.common.websocket.MyWebSocketClient
import com.jsgt.greekfire.common.websocket.MyWebSocketClientManager
import com.jsgt.greekfire.dao.model.MarketBean
import com.jsgt.greekfire.dao.viewmodel.MarketBeanViewModel
import com.jsgt.greekfire.dao.viewmodel.MarketBeanViewModelFactory
import com.jsgt.greekfire.dao.viewmodel.NetLoadResultObserver
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.event.USDTPriceEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.factory.WalletViewModelFactory
import com.jsgt.greekfire.ui.home.adapter.BannerImageAdapter
import com.jsgt.greekfire.ui.home.adapter.HomeAdapter
import com.jsgt.greekfire.ui.home.adapter.IndexDataAdapter
import com.jsgt.greekfire.ui.home.adapter.MarketAdapter
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.home.genesisblock.GenesisBlockActivity
import com.jsgt.greekfire.ui.home.menu.pool.PoolJoinActivity
import com.jsgt.greekfire.ui.home.menu.powerise.PrivilegeActivity
import com.jsgt.greekfire.ui.main.activation.ActivationActivity
import com.jsgt.greekfire.ui.market.MarketDetailActivity
import com.jsgt.greekfire.ui.trading.KLineActivity
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.jsgt.greekfire.viewmodel.WalletViewModel1
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_home.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.Serializable
import java.text.DecimalFormat


/**
 * 首页
 */
class HomeFragment : BaseFragment(), View.OnClickListener {
    private val REQUEST_ACTIVATION = 100

    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }

    private val walletViewModel1: WalletViewModel1 by lazy {
        ViewModelProvider(
            this,
            WalletViewModelFactory()
        ).get(WalletViewModel1::class.java)
    }

    private val marketBeanViewModel: MarketBeanViewModel by lazy {
        ViewModelProvider(
            this,
            MarketBeanViewModelFactory(
                requireContext(),
                resources.getStringArray(R.array.market_list)
            )
        ).get(MarketBeanViewModel::class.java)
    }

//    private val marketViewModel: MarketViewModel by lazy {
//        ViewModelProvider(
//            this,
//            MarketViewModelFactory()
//        ).get(MarketViewModel::class.java)
//    }

    //----------
    private val fileName = "menulist"
    private var strByJson: String? = null
    private val indexDataAll: ArrayList<MenuEntity> = ArrayList<MenuEntity>()
    private var indexDataList: ArrayList<MenuEntity> = ArrayList<MenuEntity>()
    private var appContext: App? = null
    private var adapter: IndexDataAdapter? = null
    private var indexDataUser: ArrayList<MenuEntity> = ArrayList<MenuEntity>()
    private var listData: ArrayList<MenuEntity> = ArrayList<MenuEntity>()


    val list: MutableList<MarketBean> = ArrayList()
    private var pwdDialog1: Dialog? = null
    var immutableSet: MutableList<MarketBean> = ArrayList()
    var immutableSet1: MutableList<MarketBean> = ArrayList()
    private val mBannerList = ArrayList<BannerBean>()
    private val marketAdapter: MarketAdapter by lazy { MarketAdapter() }
    private val homeAdapter: HomeAdapter by lazy { HomeAdapter() }
    private var sortCheck: Boolean = false
    private val df = DecimalFormat("######0.00")

    var myWebSocketClient: MyWebSocketClient? = null
    var onSocketList: MyWebSocketClient.OnSocketListener? = null

    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun onResume() {
        super.onResume()
        refreshData()
        indexDataList.clear()
        listData.clear()
        indexDataList =
            appContext?.readObject(AppConfig.KEY_USER) as ArrayList<MenuEntity>
        if (indexDataList.size > 7) {
            for (i in 0..6) {
                listData.add(indexDataList[i])
            }

        } else {
            listData.addAll(indexDataList)
        }
        val allMenuEntity = MenuEntity()
        allMenuEntity.ico = "app_addll_ico"
        allMenuEntity.id = "all"
        allMenuEntity.title  = "全部"
        listData.add(allMenuEntity)
        if (adapter == null) {
            adapter = IndexDataAdapter(requireContext(), listData)
            gv_launch_start.adapter = adapter
        } else {
            adapter!!.notifyDataSetChanged()
        }
    }

    //现在用的hide,show的方式，除了第一次后面不会走onResume了
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            refreshData()
        }
    }

    private fun refreshData() {
//        NetDataManager.getUSTDPrice()
        if (LOGIN_STATUS) {
            updateView()
            NetDataManager.getUserAssets()
            if (NetDataManager.walletInfo == null) {
                NetDataManager.getWalletInfo()
            }
        }
    }


    override fun main() {
        appContext = activity?.application as App?

        //获取公告
        userViewModel.noticeList(0,10)

        //banner 图
        initBanner()
        //添加adpter 数据
        recyclerview.isNestedScrollingEnabled = false
        recyclerview.adapter = marketAdapter
        //查询币种价格
        userViewModel.getPrice()
        initMenu()
        three_recyclerView.adapter = homeAdapter
        three_recyclerView.layoutManager = GridLayoutManager(requireActivity(), 4)

//        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { p0, verticalOffset ->
//            refresh_layout.isEnabled = verticalOffset >= 0
//        })

        refresh_layout.setOnRefreshListener {
//            NetDataManager.getUSTDPrice()
            if (LOGIN_STATUS) {
                NetDataManager.getUserAssets()
                NetDataManager.getWalletInfo()
            }
            marketBeanViewModel.getMarketList()

//            marketViewModel.getNewPrice("GFT_USDT")
            userViewModel.noticeList(0,10)
        }

        marketAdapter.itemClickListner = {
            MarketDetailActivity.start(requireContext(), it)
        }

        homeAdapter.itemClickListner = {
            if (it.symbol!!.startsWith("gft")) {
                KLineActivity.start(requireContext(), it)
            } else {
                MarketDetailActivity.start(requireContext(), it)
            }
        }

        userViewModel.getPrice.observe(requireActivity(), Observer {
//            mmkv.encode("gfcPrice", it.gfcPrice)
//            mmkv.encode("usdtPrice", it.usdtPrice)
//
//            Log.e("TAG", "gfcPrice: " + mmkv.decodeString("gfcPrice"))
//            Log.e("TAG", "usdtPrice: " + mmkv.decodeString("usdtPrice"))

        })

        userViewModel.genesisActBoolean.observe(this, Observer {
            if (it == null) {
                ToastUtils.show(requireActivity(), "活动未开启")
            } else {
                if (it == 0) {
//                    isPoolActive=false
                    ToastUtils.show(requireActivity(), "活动未开启")
                } else if (it == 1) {
//                    isPoolActive=true
                    goToActivity<GenesisBlockActivity>()
                }
            }
        })
        userViewModel.noticeListLiveData.observe(this, Observer {
            val noticeList = ArrayList<String>()
            it.forEach { it1 ->
                noticeList.add(it1.title!!)
            }
            marqueeView.startWithList(noticeList)
        })

        pwdDialog1?.dismiss()

//        walletViewModel.bindingActivation.observe(this, Observer {
//            NetDataManager.getUserAssets()
//            NetDataManager.getWalletInfo()
//            ToastUtils.show(activity!!, "激活成功")
//
//            showProgress(false)
//            pwdDialog1?.dismiss()
//        })
//        walletViewModel.errorLiveData.observe(this, Observer {
//
//            if (LOGIN_STATUS) {
//                NetDataManager.getUserAssets()
//                NetDataManager.getWalletInfo()
//            }
//            showProgress(false)
//        })

//        marketViewModel.getNewPrice("GFT_USDT")
//        marketViewModel.newPriceLiveData.observe(this, Observer {
//            val marketBean = MarketBean()
//            marketBean.symbol = "gft_usdt"
//            marketBean.last = it.newPrice
//            App.context.gftPrice = it.newPrice
//            try {
//                val per = (it.newPrice - it.lastPrice) / it.lastPrice * 100;
//                if (per >= 0) {
//                    marketBean.changePercentage = "+" + df.format(per) + "%"
//                } else {
//                    marketBean.changePercentage = "-" + df.format(per) + "%"
//                }
//            } catch (error: Exception) {
//                marketBean.changePercentage = "+" + df.format(0) + "%"
//            }
//            homeAdapter.bindGFT(marketBean)
//        })

        userViewModel.errorLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
        })

        walletViewModel1.errorLiveData.observe(this, Observer
        {
            refresh_layout.isRefreshing = false
        })

        refresh_layout.isRefreshing = true
        marketBeanViewModel.getMarketList()
        marketBeanViewModel.marketListLiveData?.observe(this, Observer {
            list.clear()
            list.addAll(it)

            immutableSet.clear()
            immutableSet1.clear()

            var index = 0
            list.forEach { it1 ->
                if (index < 4) {
                    immutableSet.add(it1)
                }
                immutableSet1.add(it1)
                index++
            }
            homeAdapter.refreshData(immutableSet)
            marketAdapter.refreshData(immutableSet1)
        })

        marketBeanViewModel.netLoadLiveData.observe(this, object : NetLoadResultObserver() {
            override fun onSuccess() {
                refresh_layout.isRefreshing = false
            }

            override fun onError(msg: String?) {
                refresh_layout.isRefreshing = false
            }
        })

//        marketViewModel.errorLiveData.observe(this, Observer
//        {
//        })

//        myWebSocketClient = MyWebSocketClientManager.instance.createClient()
//        onSocketList = object : MyWebSocketClient.OnSocketListener {
//            override fun onOpen(handshakedata: ServerHandshake?) {
//            }
//
//            override fun onMessage(
//                message1: Message<GFTKLineData?>?,
//                message2: Message<NewPrice?>?,
//                message3: Message<TickMarket?>?
//            ) {
//                if (message2 != null) {
//                    marketViewModel.newPriceLiveData.postValue(message2.data)
//                }
//            }
//
//            override fun onClose(code: Int, reason: String?, remote: Boolean) {
//                myWebSocketClient!!.reconnectBlocking()
//            }
//
//            override fun onError(ex: java.lang.Exception?) {
//            }
//
//        }
//        myWebSocketClient!!.addOnSocketListener(onSocketList)
//        myWebSocketClient!!.connect()
    }

    private fun initMenu() {
        gv_launch_start.isFocusable = false
        //初始化全部菜单
        strByJson = getJson(requireContext(), fileName)
        val objectMapper = ObjectMapper()
        val data:List<MenuEntity> = objectMapper.readValue(strByJson, object:TypeReference<List<MenuEntity>>(){})

//        val jsonArray = JSON.parseArray(strByJson,MenuEntity::class.java)
        for (menuEntity in data) {
            //判断是否显示
            if (!menuEntity.hide) {
                indexDataAll.add(menuEntity)
            }
        }

        appContext?.saveObject(indexDataAll as Serializable, AppConfig.KEY_All)

        val serializable = appContext?.readObject(AppConfig.KEY_USER)
        if (serializable != null) {
            indexDataUser = serializable as ArrayList<MenuEntity>
        }

        if (indexDataUser.size == 0) {
            appContext?.saveObject(indexDataAll as Serializable, AppConfig.KEY_USER)
        } else {
            //用于版本升级后，判断已选择菜单中是否显示
            for (index in indexDataUser.size - 1 downTo 0) {
                if (!indexDataAll.contains(indexDataUser[index])) {
                    indexDataUser.removeAt(index)
                }
            }
            appContext?.saveObject(indexDataUser as Serializable, AppConfig.KEY_USER)
        }

        LogUtils.error(strByJson)
        gv_launch_start.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                val title = listData[position].title
                val strId = listData[position].id
                LogUtils.error(title + strId)
                if (strId == "all") {
                    // 更多
                    goToActivity<MenuManageActivity>()
                } else {
                    title?.let {
                        when (it) {
                            "云创智" -> {
                                if (LOGIN_STATUS) {
                                    if (NetDataManager.walletInfo?.walletLevel == 2 || NetDataManager.walletInfo?.walletLevel == 4) {
                                        goToActivity<PrivilegeActivity> {
                                            putExtra(PrivilegeActivity.TYPE_STR, 0)
                                        }
                                    } else {
                                        showToast(getString(R.string.not_permission))
                                    }
                                } else {
                                    goToActivity<EntranceActivity>()
                                }
                            }
                            "云创联" -> {
                                if (LOGIN_STATUS) {
                                    if (NetDataManager.walletInfo?.walletLevel == 3 || NetDataManager.walletInfo?.walletLevel == 4) {
                                        goToActivity<PrivilegeActivity> {
                                            putExtra(PrivilegeActivity.TYPE_STR, 1)
                                        }
                                    } else {
                                        showToast(getString(R.string.not_permission))
                                    }
                                } else {
                                    goToActivity<EntranceActivity>()
                                }
                            }
                            "云矩阵" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "云榜单" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "云矿场" -> {
                                if (LOGIN_STATUS) {
                                    if (IS_ACTIVATION != 1) {
//                                        goToActivity<PoolActivity>()
                                        goToActivity<PoolJoinActivity>() {
                                            putExtra("type", "CLOUD_MINE")
                                        }
                                    } else {
                                        showToast(getString(R.string.not_yet_activation))
                                    }
                                } else {
                                    goToActivity<EntranceActivity>()
                                }
                            }
                            "云矿池" -> {
                                if (LOGIN_STATUS) {
                                    if (IS_ACTIVATION != 1) {
//                                        goToActivity<PoolActivity>()
//                                        goToActivity<PoolJoinActivity>()
//                                        ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                                        goToActivity<PoolJoinActivity>() {
                                            putExtra("type", "CLOUD_POOL")
                                        }
                                    } else {
                                        showToast(getString(R.string.not_yet_activation))
                                    }
                                } else {
                                    goToActivity<EntranceActivity>()
                                }
                            }
                            "云投票" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "云激活" -> {
                                if (LOGIN_STATUS) {
                                    goToActivityForResult<ActivationActivity>(REQUEST_ACTIVATION)
                                } else {
                                    goToActivity<EntranceActivity>()
                                }
                            }
                            "开源钱包" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "社交加密" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "私域社群" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "人工智能" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "云游戏" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "全球支付" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "区块游览" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "发行项目" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "分布式商业" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }
                            "全球节点" -> {
                                ToastUtils.show(requireContext(), getString(R.string.not_yet_open))
                            }

                        }
                    }

                }
            }
    }

    override fun onDestroyView() {
        MyWebSocketClientManager.instance.destroyClient(onSocketList)
        myWebSocketClient = null

        if (marqueeView != null) {
            if (marqueeView.isFlipping) {
                marqueeView.stopFlipping();
            }
        }
        super.onDestroyView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ACTIVATION && resultCode == RESULT_OK) {
            NetDataManager.getWalletInfo()
        }
    }

    private fun initBanner() {
        mBannerList.add(BannerBean(R.mipmap.banner3))

        var adapter = BannerImageAdapter(mBannerList)
        home_banner?.let {
            it.addBannerLifecycleObserver(this)
            it.indicator = CircleIndicator(requireContext())
            it.setBannerRound(20f)
            it.adapter = adapter
        }
        home_banner.setOnBannerListener { data, position ->
            //showToast(position.toString())

        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {

        }
    }

    private fun updateView() {

    }
//
//    private fun updateMoneyScale() {
//        home_income_tv.text = "¥ ${PriceFormatUtil.format(MONEY_SCALE, 2)}"
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTransferEvent(e: TransferEvent) {
        if (LOGIN_STATUS) {
            NetDataManager.getUserAssets()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        updateView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUSDTPriceEvent(e: USDTPriceEvent) {
//        updateMoneyScale()
    }

    fun popwindos() {

        val contentView = layoutInflater.inflate(R.layout.dialog_transfer_pop, null, false)
        pwdDialog1 = DialogUtil.show(requireActivity(), contentView)
        pwdDialog1?.setOnDismissListener {
            pwdDialog1 = null
        }
        pwdDialog1?.setCanceledOnTouchOutside(true)
        pwdDialog1?.setCancelable(true)
        pwdDialog1?.show()
        val pwd = contentView.findViewById<EditText>(R.id.pwd_2)
        pwd.isSingleLine = false
        contentView.findViewById<TextView>(R.id.pop_sure).setOnClickListener {
            val pwd = contentView.findViewById<EditText>(R.id.pwd_2).text.toString().trim()

            if (TextUtils.isEmpty(pwd)) {
                showToast(getString(R.string.please_addrees))
            } else {
//                //服务端验证
                walletViewModel1.bindingActivation(pwd)
                pwdDialog1?.dismiss()
                showProgress(false)

            }
        }
    }

    private fun getJson(context: Context, fileName: String?): String? {
        val stringBuilder = StringBuilder()
        try {
            val assetManager = context.assets
            val bf = BufferedReader(
                InputStreamReader(
                    assetManager.open(fileName!!)
                )
            )
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
            LogUtils.error(e.toString())
        }
        return stringBuilder.toString()
    }
}